package MainPackage;

import com.google.gdata.client.health.HealthService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.TextContent;
import com.google.gdata.data.health.ProfileEntry;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

// <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
// #[regen=yes,id=DCE.523A107B-9A2A-D4DA-F39A-806179F38C78]
// </editor-fold> 
public class Upload {

    protected static final String TITLE = "CCR";
    protected static HealthService service;
    protected final static String USERNAME = "if07b071@technikum-wien.at";
    protected final static String PASSWORD = "googlehealth";
    protected static final String FEED_BASE_PATH =
            "https://www.google.com/health/feeds/";
    protected static final String PROFILE_FEED_PATH = FEED_BASE_PATH + "profile/";
    protected static final String REGISTER_FEED_PATH = FEED_BASE_PATH + "register/";
    protected static String FEED_UPLOAD_PATH = REGISTER_FEED_PATH + "ui/";
    protected static final String PROFILE_LIST_URL_PATH = PROFILE_FEED_PATH + "list";
    private static List<String> profileIds = null;
    protected static String profileID = "";

    // <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
    // #[regen=yes,id=DCE.80331C51-FA4E-E164-9BF3-911BD4608C94]
    // </editor-fold> 
    public Upload() {
    }

    public static void main(String[] args) {
    }

    // <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
    // #[regen=yes,id=DCE.49F707C5-8B24-FDB2-4037-80B5B13A55F6]
    // </editor-fold> 
    protected static boolean establishConnection(String file) {
        try {
            /*
            try {
            String dataToEstablishConnection = URLEncoder.encode("accountType", "UTF-8") + "=" + URLEncoder.encode("HOSTED_OR_GOOGLE", "UTF-8");
            dataToEstablishConnection += URLEncoder.encode("Email", "UTF-8") + "=" + URLEncoder.encode("if07b071@technikum-wien.at", "UTF-8");
            dataToEstablishConnection += URLEncoder.encode("Email", "UTF-8") + "=" + URLEncoder.encode("if07b071@technikum-wien.at", "UTF-8");
            URL url = new URL("https://www.google.com/accounts/ClientLogin");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(dataToEstablishConnection);
            wr.flush();
            } catch (IOException ex) {
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
            } */

            service = new HealthService("Google Health Demo");
            service.setUserCredentials(USERNAME, PASSWORD);

            //Holt sich alle Profile von Google, wir haben nur eins, daher wird das erste Profil genommen!
            profileIds = new ArrayList<String>();
            Feed profileListFeed = service.getFeed(
                    new URL(PROFILE_LIST_URL_PATH), Feed.class);
            for (Entry profileListEntry : profileListFeed.getEntries()) {
                profileIds.add(
                        ((TextContent) profileListEntry.getContent()).getContent().getPlainText());
            }
            profileID = profileIds.get(0);
            FEED_UPLOAD_PATH += profileID;

            FileReader fr = new FileReader(file);

            String xmlString = "";
            BufferedReader bufRead = new BufferedReader(fr);
            String line;
            int count = 0;
            line = bufRead.readLine();
            count++;
            while (line != null) {
                xmlString += line;
                line = bufRead.readLine();
                count++;
            }
            bufRead.close();
            fr.close();

            ProfileEntry entry = new ProfileEntry();
            entry.setTitle(new PlainTextConstruct(TITLE));
            XmlBlob blob = new XmlBlob();
            blob.setBlob(xmlString);
            entry.setXmlBlob(blob);
//            ContinuityOfCareRecord ccr = new ContinuityOfCareRecord();
//            ccr.setXmlBlob(blob);
//            entry.setContinuityOfCareRecord(ccr);
            ProfileEntry createdEntry = service.insert(new URL(FEED_UPLOAD_PATH), entry);
            System.out.println("XML sent");
//
//            Query query = new Query(new URL("https://www.google.com/health/feeds/register/ui/" + profileID));
//
//                RegisterFeed result = service.query(query, RegisterFeed.class);
//
//                for (RegisterEntry entry2 : result.getEntries()) {
//                    // Display author
//                    System.out.println(entry2.getAuthors().get(0).getName());
//
//                    // Display date sent
//                    System.out.println(entry2.getPublished().toString());
//
//                    // Get subject of notice
//                    System.out.println(entry2.getTitle().getPlainText());
//
//                    // Get notice message body
//                    TextContent content = (TextContent) entry2.getContent();
//                    System.out.println(content.getContent().getPlainText());
//
//                    // Print out CCR information attached to the notice
//                    if (entry2.getXmlBlob().getBlob().length() > 0) {
//                        System.out.println(entry2.getXmlBlob().getBlob());
//
//                }
//            }



            /*URL url = new URL(FEED_UPLOAD_PATH);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter outw = new OutputStreamWriter(conn.getOutputStream());
            outw.write(xmlString);
            outw.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String outline;
            while ((outline = rd.readLine()) != null) {
            System.out.println(outline);
            }
            System.out.println(FEED_UPLOAD_PATH);
            outw.close();
            rd.close();*/






            return true;
        } catch (IOException ex) {
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServiceException ex) {
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    // <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
    // #[regen=yes,id=DCE.C5689939-3B43-CCE4-E86D-2D5212460DDF]
    // </editor-fold> 
    protected boolean uploadPatient() {
        return true;
    }

// <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
// #[regen=yes,id=DCE.6485BD0B-C55E-691F-CE02-689322025E96]
// </editor-fold> 
    protected ArrayList<Integer> Unnamed() {
        return null;
    }
}

